package com.dongxing.concyrrency.chapter6;

/**
 * @author XavierDong
 **/
public class ThreadService {

    private Thread executeThread;

    private Boolean finished = Boolean.FALSE;

    public void execute(Runnable task) {

        executeThread = new Thread() {
            @Override
            public void run() {
                Thread runner = new Thread(task);
                runner.setDaemon(true);
                runner.start();
                try {
                    runner.join();
                    finished = Boolean.TRUE;
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        };
        executeThread.start();

    }

    public void shutdown(Long mills) {
        Long currentTime = System.currentTimeMillis();
        while (!finished) {
            if ((System.currentTimeMillis() - currentTime) >= mills) {
                System.out.println("任务超时，需要结束");
                executeThread.interrupt();
                break;
            }

            try {
                executeThread.sleep(1);
            } catch (InterruptedException e) {
                System.out.println("这种情况是执行线程被打断");
                break;
            }
        }
        finished = Boolean.FALSE;
    }

}
